{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# High-level PyTorch Example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "import numpy as np\n",
    "import math\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "import torch.optim as optim\n",
    "import torch.utils.data as data_utils\n",
    "import torch.nn.init as init\n",
    "from torch.autograd import Variable\n",
    "from common.params import *\n",
    "from common.utils import *"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Big impact on training-time (from 350 to 165s)\n",
    "torch.backends.cudnn.benchmark=True # enables cudnn's auto-tuner"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OS:  linux\n",
      "Python:  3.5.2 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:53:06) \n",
      "[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]\n",
      "PyTorch:  0.2.0_4\n",
      "Numpy:  1.13.3\n",
      "GPU:  ['Tesla K80']\n"
     ]
    }
   ],
   "source": [
    "print(\"OS: \", sys.platform)\n",
    "print(\"Python: \", sys.version)\n",
    "print(\"PyTorch: \", torch.__version__)\n",
    "print(\"Numpy: \", np.__version__)\n",
    "print(\"GPU: \", get_gpu_name())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "class SymbolModule(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(SymbolModule, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(3, 50, kernel_size=3, padding=1)\n",
    "        self.conv2 = nn.Conv2d(50, 50, kernel_size=3, padding=1)\n",
    "        self.conv3 = nn.Conv2d(50, 100, kernel_size=3, padding=1)\n",
    "        self.conv4 = nn.Conv2d(100, 100, kernel_size=3, padding=1)\n",
    "        # feature map size is 8*8 by pooling\n",
    "        self.fc1 = nn.Linear(100*8*8, 512)\n",
    "        self.fc2 = nn.Linear(512, N_CLASSES)\n",
    "\n",
    "    def forward(self, x):\n",
    "        \"\"\" PyTorch requires a flag for training in dropout \"\"\"\n",
    "        x = self.conv2(F.relu(self.conv1(x)))\n",
    "        x = F.relu(F.max_pool2d(x, kernel_size=2, stride=2))\n",
    "        x = F.dropout(x, 0.25, training=self.training)\n",
    "\n",
    "        x = self.conv4(F.relu(self.conv3(x)))\n",
    "        x = F.relu(F.max_pool2d(x, kernel_size=2, stride=2))\n",
    "        x = F.dropout(x, 0.25, training=self.training)\n",
    "\n",
    "        x = x.view(-1, 100*8*8)   # reshape Variable\n",
    "        x = F.dropout(F.relu(self.fc1(x)), 0.5, training=self.training)\n",
    "        # nn.CrossEntropyLoss() contains softmax, don't apply twice\n",
    "        #return F.log_softmax(x)\n",
    "        return self.fc2(x)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "def init_model(m):\n",
    "    # Implementation of momentum:\n",
    "    # v = \\rho * v + g \\\\\n",
    "    # p = p - lr * v\n",
    "    opt = optim.SGD(m.parameters(), lr=LR, momentum=MOMENTUM)\n",
    "    criterion = nn.CrossEntropyLoss()\n",
    "    return opt, criterion"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preparing train set...\n",
      "Preparing test set...\n",
      "(50000, 3, 32, 32) (10000, 3, 32, 32) (50000,) (10000,)\n",
      "float32 float32 int64 int64\n",
      "CPU times: user 904 ms, sys: 559 ms, total: 1.46 s\n",
      "Wall time: 1.46 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Data into format for library\n",
    "x_train, x_test, y_train, y_test = cifar_for_library(channel_first=True)\n",
    "# Torch-specific\n",
    "y_train = y_train.astype(np.int64)\n",
    "y_test = y_test.astype(np.int64)\n",
    "print(x_train.shape, x_test.shape, y_train.shape, y_test.shape)\n",
    "print(x_train.dtype, x_test.dtype, y_train.dtype, y_test.dtype)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 1.52 s, sys: 465 ms, total: 1.98 s\n",
      "Wall time: 2.02 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "sym = SymbolModule()\n",
    "sym.cuda() # CUDA!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 111 µs, sys: 47 µs, total: 158 µs\n",
      "Wall time: 160 µs\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "optimizer, criterion = init_model(sym)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "6\n",
      "7\n",
      "8\n",
      "9\n",
      "CPU times: user 2min 24s, sys: 24.7 s, total: 2min 48s\n",
      "Wall time: 2min 49s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# 169s\n",
    "# Sets training = True\n",
    "sym.train()  \n",
    "for j in range(EPOCHS):\n",
    "    for data, target in yield_mb(x_train, y_train, BATCHSIZE, shuffle=True):\n",
    "        # Get samples\n",
    "        data = Variable(torch.FloatTensor(data).cuda())\n",
    "        target = Variable(torch.LongTensor(target).cuda())\n",
    "        # Init\n",
    "        optimizer.zero_grad()\n",
    "        # Forwards\n",
    "        output = sym(data)\n",
    "        # Loss\n",
    "        loss = criterion(output, target)\n",
    "        # Back-prop\n",
    "        loss.backward()\n",
    "        optimizer.step()\n",
    "    # Log\n",
    "    print(j)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "CPU times: user 910 ms, sys: 104 ms, total: 1.01 s\n",
      "Wall time: 1.01 s\n"
     ]
    }
   ],
   "source": [
    "%%time\n",
    "# Test model\n",
    "# Sets training = False\n",
    "sym.eval()\n",
    "n_samples = (y_test.shape[0]//BATCHSIZE)*BATCHSIZE\n",
    "y_guess = np.zeros(n_samples, dtype=np.int)\n",
    "y_truth = y_test[:n_samples]\n",
    "c = 0\n",
    "for data, target in yield_mb(x_test, y_test, BATCHSIZE):\n",
    "    # Get samples\n",
    "    data = Variable(torch.FloatTensor(data).cuda())\n",
    "    # Forwards\n",
    "    output = sym(data)\n",
    "    pred = output.data.max(1)[1].cpu().numpy().squeeze()\n",
    "    # Collect results\n",
    "    y_guess[c*BATCHSIZE:(c+1)*BATCHSIZE] = pred\n",
    "    c += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Accuracy:  0.776542467949\n"
     ]
    }
   ],
   "source": [
    "print(\"Accuracy: \", sum(y_guess == y_truth)/len(y_guess))"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
